﻿using HuaYun.FTP;
using HuaYun.FTPUpload.Controls;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HuaYun.FTPUpload
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public string IniPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "config.ini"; }
        }

        public string FTPUserName { get; set; }

        public string FTPPassword { get; set; }

        public string FTPAddress { get; set; }

        public int FTPPort { get; set; }

        /// <summary>
        /// 选择框窗体
        /// </summary>
        private Dictionary<string, UCFileItem> DicFileItems = new Dictionary<string, UCFileItem>();

        /// <summary>
        /// 是否开始上传了
        /// </summary>
        private bool IsStartUpload = false;

        /// <summary>
        /// 检查是否上传成功
        /// </summary>
        private Thread th_CheckUpload = null;

        /// <summary>
        /// 是否检查线程
        /// </summary>
        private bool IsContinueCheck = true;

        /// <summary>
        /// 是否已经执行
        /// </summary>
        private bool IsExcute = false;

        public MainWindow()
        {
            InitializeComponent();
            Init();

            this.Closing += MainWindow_Closing;
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Process[] process = Process.GetProcessesByName("HuaYun.FTPUpload.exe");
            foreach (var item in process)
                item.Kill();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            th_CheckUpload = new Thread(CheckUploadFile);
            th_CheckUpload.IsBackground = true; // 设置为后台线程，当主线程退出时该线程也会退出
            th_CheckUpload.Start();
        }

        private void DragMove_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void btnTitle_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button)
            {
                Button btn = sender as Button;

                if (btn.Name == "btnMini")
                {
                    this.WindowState = WindowState.Minimized;
                }
                else
                {
                    Application.Current.Shutdown(0);
                }
            }
        }

        FTPClient client;

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            int port = Convert.ToInt32(txtFTPPort.Text);
            client = new FTPClient(txtAddress.Text, port, txtFTPUserName.Text, txtFTPPassword.Password, FTPModel.ASCII, Encoding.Default);
            client.OnProgressChanged += client_OnProgressChanged;
            client.OnCompleted += client_OnCompleted;
            client.OnFailed += client_OnFailed;

            int result = client.Connect();

            if (result == 0)
            {
                lblMsg.Content = "成功登陆.";

                INIOperationClass.INIWriteValue(IniPath, "USER", "Address", txtAddress.Text);
                INIOperationClass.INIWriteValue(IniPath, "USER", "UserName", txtFTPUserName.Text);
                INIOperationClass.INIWriteValue(IniPath, "USER", "Password", txtFTPPassword.Password);
                INIOperationClass.INIWriteValue(IniPath, "USER", "Port", txtFTPPort.Text);

                FTPAddress = txtAddress.Text;
                FTPUserName = txtFTPUserName.Text;
                FTPPassword = txtFTPPassword.Password;
                FTPPort = Convert.ToInt32(txtFTPPort.Text);
            }
            else
            {
                lblMsg.Content = "成功失败,错误码:" + result;
            }
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button)
            {
                Button btn = sender as Button;

                switch (btn.Name)
                {
                    default:
                        break;
                    case "btnSelectFile":
                        Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
                        dialog.Multiselect = true;

                        if (dialog.ShowDialog() == true && dialog.FileNames.Length > 0)
                            AddFiles(dialog.FileNames);
                        break;
                    case "btnUpload":
                        this.Cursor = Cursors.Wait;
                        Upload();
                        this.Cursor = Cursors.Arrow;
                        break;
                }
            }
        }

        private void client_OnProgressChanged(string sessionID, string progress)
        {
            lblMsg.Content = sessionID + "/" + progress;
        }

        private void client_OnCompleted(string sessionID)
        {
            lblMsg.Content = "complete:" + sessionID;
        }

        private void client_OnFailed(string sessionID, int error)
        {
            lblMsg.Content = "failed:" + sessionID + ",Code:" + error;
        }

        public void CheckUploadFile()
        {
            while (IsContinueCheck)
            {
                try
                {
                    // 包含待上传文件 并且开始上传后 进行检查
                    if (DicFileItems.Values.Count > 0 && IsStartUpload)
                    {
                        Dictionary<string, string> removeKeys = new Dictionary<string, string>();
                        foreach (var keyValue in DicFileItems)
                        {
                            if (keyValue.Value.IsComplete)
                            {
                                IsExcute = false;
                                if (!removeKeys.ContainsKey(keyValue.Key))
                                    removeKeys.Add(keyValue.Key, "");
                            }
                            else
                            {
                                if (keyValue.Value.Precent.Contains("100"))
                                {
                                    IsExcute = false;
                                    if (!removeKeys.ContainsKey(keyValue.Key))
                                        removeKeys.Add(keyValue.Key, "");
                                }
                            }
                        }
                        if (removeKeys.Count > 0 && !IsExcute)
                            this.Dispatcher.BeginInvoke(new Action(() =>
                            {
                                IsExcute = true;
                                try
                                {
                                    foreach (var item in removeKeys)
                                    {
                                        if (DicFileItems.ContainsKey(item.Key))
                                        {
                                            if (stackImage.Children.Contains(DicFileItems[item.Key]))
                                                stackImage.Children.Remove(DicFileItems[item.Key]);
                                            DicFileItems.Remove(item.Key);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    lblMsg.Content = "当前执行有异常:" + ex.Message;
                                    IsContinueCheck = false;
                                }
                            }));
                    }
                }
                catch (Exception ex)
                {

                }
                Thread.Sleep(2 * 1000);
            }
        }

        private void AddFiles(string[] fileNames)
        {
            List<string> imageExtList = new List<string> { ".jpg", ".bmp", ".jpeg", ".png", ".gif" };

            foreach (var fileName in fileNames)
            {
                if (!DicFileItems.ContainsKey(fileName))
                {
                    UCFileItem item = new UCFileItem(stackImage, DicFileItems);
                    item.LocalPath = fileName;
                    item.Width = 150;
                    item.Height = 140;
                    item.FTPUserName = FTPUserName;
                    item.FTPPassword = FTPPassword;
                    item.FTPAddress = FTPAddress;
                    item.FTPPort = FTPPort;

                    string fileExt = fileName.Substring(fileName.LastIndexOf('.'));
                    if (imageExtList.Contains(fileExt.ToLower()))
                        item.InitImageView(2);
                    else
                        item.InitImageView(1);

                    stackImage.Children.Add(item);
                    DicFileItems.Add(fileName, item);
                }
            }
        }

        private void Upload()
        {
            try
            {
                if (DicFileItems.Count > 0)
                {
                    IsStartUpload = true;

                    foreach (var item in DicFileItems.Values.Where(m => !m.IsUpload))
                        item.StartUpload();
                }
            }
            catch (Exception ex)
            {
                //Log.Error(ex);
            }
        }

        private void Init()
        {
            FTPAddress = txtAddress.Text = INIOperationClass.INIGetStringValue(IniPath, "USER", "Address", null);
            FTPUserName = txtFTPUserName.Text = INIOperationClass.INIGetStringValue(IniPath, "USER", "UserName", null);
            FTPPassword = txtFTPPassword.Password = INIOperationClass.INIGetStringValue(IniPath, "USER", "Password", null);
            txtFTPPort.Text = INIOperationClass.INIGetStringValue(IniPath, "USER", "Port", null);
            FTPPort = Convert.ToInt32(txtFTPPort.Text);
        }

    }
}
